package com.app.mingluxing.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

import com.app.mingluxing.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 *
 * 制作 防 微信头像的 工具
 * Created by Aaron on 16/5/24.
 */
public class GroupFaceUtils {

    /**
     * 图片之间的距离
     */
    private static int PADDING = 2;
    /**
     * 圆角值
     */
    private static final int ROUNDPX = 5;

//	/** 头像模式 圆的 */
//	public static final int FACETYPE_QQ = 1;
    /**
     * 头像模式 方的 最多9个
     */
//    public static final int FACETYPE_WS = 2;

    public static Bitmap createGroupFace(Context context,
//                                         Bitmap[] bitmapArray) {
                                         List<String> imageUrls) {

        if (imageUrls == null || imageUrls.size() < 1) {
            return null;
        }

        Bitmap[] bitmapArray = new Bitmap[imageUrls.size()];
        //把图片地址变成bitmap
        for (int i = 0; i < imageUrls.size(); i++) {

            bitmapArray[i] = getNetWorkBitmap(context, imageUrls.get(i));

        }


//		if (type == FACETYPE_QQ) {
//			return createGroupBitCircle(bitmapArray, context);
//		}
        return createTogetherBit(bitmapArray, context);
    }

    private static Bitmap scaleBitmap(float paramFloat, Bitmap paramBitmap) {
        Matrix localMatrix = new Matrix();
        localMatrix.postScale(paramFloat, paramFloat);
        return Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(),
                paramBitmap.getHeight(), localMatrix, true);
    }

//	/**
//	 * 拼接群头像 圆形版的
//	 *
//	 * @param bitmapArray
//	 * @param context
//	 * @return
//	 */
//	private static Bitmap createGroupBitCircle(Bitmap[] bitmapArray,
//			Context context) {
//		if (bitmapArray.length < 1 && bitmapArray.length > 9) {
//			return null;
//		}
//		// 先取一个获取宽和高
//		Bitmap tempBitmap = (Bitmap) bitmapArray[0];
//		if (tempBitmap == null) {
//			return null;
//		}
//		// 画布的宽
//		int tempWidth = tempBitmap.getWidth();
//		// 画布的高
//		int tempHeight = tempBitmap.getHeight();
//		Bitmap canvasBitmap = Bitmap.createBitmap(tempWidth, tempHeight,
//				Bitmap.Config.ARGB_8888);
//		Canvas localCanvas = new Canvas(canvasBitmap);
//		localCanvas.drawColor(Color.GRAY);
//		JoinBitmaps.join(localCanvas, Math.min(tempWidth, tempHeight),
//				Arrays.asList(bitmapArray));
//		return canvasBitmap;
//	}

    /**
     * 拼接群头像
     *
     * @param paramList
     * @param context
     * @return 头像本地路径
     */
    @SuppressWarnings("unused")
    private static Bitmap createTogetherBit(Bitmap[] paramList,
                                            final Context context) {
        if (paramList.length < 1 && paramList.length > 9) {
            return null;
        }

        // 先取一个获取宽和高
        Bitmap tempBitmap = (Bitmap) paramList[0];
        if (tempBitmap == null) {
            return null;
        }

        int dip2px = DensityUtil.dip2px(context, 60);
        // 画布的宽
        int tempWidth = dip2px;
//        int tempWidth = tempBitmap.getWidth();
        // 画布的高
        int tempHeight = dip2px;
//        int tempHeight = tempBitmap.getHeight();

        // 创建一个空格的bitmap
        Bitmap canvasBitmap = Bitmap.createBitmap(tempWidth, tempHeight,
                Bitmap.Config.RGB_565);
        // 头像的数量
        int bitmapCount = paramList.length;
        Canvas localCanvas = new Canvas(canvasBitmap);
        localCanvas.drawColor(Color.LTGRAY);
        int colum = 0;
        if (bitmapCount > 0 && bitmapCount < 5) {
            colum = 2;
        } else if (bitmapCount > 4 && bitmapCount < 10) {
            colum = 3;
        }
        float scale = 1.0F / colum;
        // 根据列数缩小
        Bitmap scaledBitmap = scaleBitmap(scale, tempBitmap);
        if (PADDING > 0) {
            PADDING = DensityUtil.dip2px(context, PADDING);
            // 如果有内边距 再次缩小
            float paddingScale = (float) (tempWidth - (colum + 1) * PADDING)
                    / colum / scaledBitmap.getWidth();
            scaledBitmap = scaleBitmap(paddingScale, scaledBitmap);
            scale = scale * paddingScale;
        }
        // 第一行的 头像个数
        int topRowCount = bitmapCount % colum;
        // 满行的行数
        int rowCount = bitmapCount / colum;
        if (topRowCount > 0) {
            // 如果第一行头像个数大于零 行数加1
            rowCount++;
        } else if (topRowCount == 0) {
            // 6 或者 9 第一行头像个数和列数一致
            topRowCount = colum;
        }
        // 缩小后头像的宽
        int scaledWidth = scaledBitmap.getWidth();
        // 缩小后头像的高
        int scaledHeight = scaledBitmap.getHeight();
        // 第一个头像与画布顶部的距离
        int firstTop = ((tempHeight - (rowCount * scaledHeight + (rowCount + 1)
                * PADDING)) / 2)
                + PADDING;
        // 第一个头像与画布左部的距离
        int firstLeft = ((tempWidth - (topRowCount * scaledWidth + (topRowCount + 1)
                * PADDING)) / 2)
                + PADDING;
        for (int i = 0; i < paramList.length; i++) {
            if (i == 9) {// 达到上限 停止
                break;
            }
            // 按照最终压缩比例压缩
            Bitmap bit = scaleBitmap(scale, (Bitmap) paramList[i]);
            if (ROUNDPX > 0) {
                // 圆角化
                bit = GetRoundedCornerBitmap(bit);
            }
            localCanvas.drawBitmap(bit, firstLeft, firstTop, null);
            firstLeft += (scaledWidth + PADDING);
            if (i == topRowCount - 1 | tempWidth - firstLeft < scaledWidth) {
                firstTop += (scaledHeight + PADDING);
                firstLeft = PADDING;
            }
            bit.recycle();
        }
        // 重置padding
        PADDING = 2;
        localCanvas.save(Canvas.ALL_SAVE_FLAG);
        localCanvas.restore();
        return canvasBitmap;
    }

    /**
     * 圆角
     *
     * @param bitmap
     * @return
     */
    private static Bitmap GetRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, ROUNDPX, ROUNDPX, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());

            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }

    private static Bitmap getNetWorkBitmap(Context ctx, String urlString) {

        //如果头像为空,则返回默认的头像
        if (CommonUtils.isNull(urlString)) {

            return BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.temp_pic);
        }

        URL imgUrl = null;
        Bitmap bitmap = null;

        try {
            imgUrl = new URL(urlString);
            // 使用HttpURLConnection打开连接
            HttpURLConnection urlConn = (HttpURLConnection) imgUrl
                    .openConnection();
            urlConn.setDoInput(true);
            urlConn.connect();
            // 将得到的数据转化成InputStream
            InputStream is = urlConn.getInputStream();
            // 将InputStream转换成Bitmap

//            bytes = inputStreamTOByte(is);

            bitmap = BitmapFactory.decodeStream(is);

            is.close();
        } catch (MalformedURLException e) {
//            System.out.println("[getNetWorkBitmap->]MalformedURLException");
            e.printStackTrace();
        } catch (IOException e) {
//            System.out.println("[getNetWorkBitmap->]IOException");
            e.printStackTrace();
        }
        return bitmap;
    }

}
